﻿using AutoMapper;
using B.S.BaseData.Domain.Entities.Meeting;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.WriteAPI.Utils;
using B.S.DataBase.EFCoreServiers.Dtos.Meetings;
using B.S.DataBase.EFCoreServiers.IServices.Meetings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace B.S.BaseData.WriteAPI.Controllers
{
    /// <summary>
    /// 会议室管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    [ApiExplorerSettings(GroupName = "MeetingRoom")]
    //[LogOperation("会议室管理操作")]
    public class MeetingRoomController : ControllerBase
    {
        private readonly IMeetingRoomServices _meetingRoomServices;
        private readonly ILogger<MeetingRoomController> _logger;
        private readonly IWebHostEnvironment env;
        private readonly IConfiguration configuration;

        public MeetingRoomController(
            IMeetingRoomServices meetingRoomServices,
            ILogger<MeetingRoomController> logger, IWebHostEnvironment env, IConfiguration configuration)
        {
            _meetingRoomServices = meetingRoomServices;
            _logger = logger;
            this.env = env;
            this.configuration = configuration;
        }

        /// <summary>
        /// 添加会议室
        /// </summary>
        [HttpPost]
        [LogOperation("会议室管理", "新增", "添加新的会议室")]
        public async Task<ApiResult> AddMeetingRoom(AddMeetingRoomDto addMeetingRoomDto)
        {
            try
            {
                var result = await _meetingRoomServices.AddMeetingRoomAsync(addMeetingRoomDto);
                if (result.IsSuc)
                {
                    _logger.LogInformation("添加会议室成功: {Name}", addMeetingRoomDto.Name);
                }
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加会议室失败");
                return ApiResult.Fail("添加会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 更新会议室信息
        /// </summary>
        [HttpPut]
        [LogOperation("会议室管理", "修改", "更新会议室信息")]
        public async Task<ApiResult> UpdateMeetingRoom([FromBody] UpdateMeetingRoomDto updateMeetingRoom)
        {
            try
            {
                var result = await _meetingRoomServices.UpdateMeetingRoomAsync(updateMeetingRoom);
                if (result.IsSuc)
                {
                    _logger.LogInformation("更新会议室成功: {Name}", updateMeetingRoom.Name);
                }
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新会议室失败");
                return ApiResult.Fail("更新会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 删除会议室
        /// </summary>
        [HttpDelete]
        [LogOperation("会议室管理", "删除", "删除会议室")]
        public async Task<ApiResult> DeleteMeetingRoom(int id)
        {
            try
            {
                var result = await _meetingRoomServices.DeleteMeetingRoomAsync(id);
                if (result.IsSuc)
                {
                    _logger.LogInformation("删除会议室成功: {Id}", id);
                }
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除会议室失败");
                return ApiResult.Fail("删除会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [LogOperation("文件上传管理", "文件上传", "上传图片")]
        public Task<IActionResult> Upload(IFormFile formFile)
        {
            //文件大小 formFile.Length的默认单位是字节（b） /1024后是KB 再/1024是MB
            // 计算文件大小（MB）
            // formFile.Length的默认单位是字节(Byte)
            // 第一次除以1024转换为KB(千字节)
            // 第二次除以1024转换为MB(兆字节)
            var fileSize = formFile.Length / 1024 / 1024;
            //(configuration["UploadConfig:Limit"]) 读取配置文件里的上传限制   ：冒号表示UploadConfig里的Limit属性  Convert.ToInt64是转换成长整型
            if (fileSize > Convert.ToInt64(configuration["UploadConfig:Limit"]))
            {
                throw new Exception("上传文件大小超过限制");
            }

            //文件后缀    获取文件扩展名并转换为小写
            var fileExt = Path.GetExtension(formFile.FileName).ToLower();
            //检查文件扩展名是否在允许的列表中 Trim去除.
            if (!configuration["UploadConfig:ExtName"].Split(',').Any(x => x == fileExt.Trim('.')))
            {
                throw new Exception("上传文件格式不正确");
            }
            //创建目录  env.WebRootPath是wwwroot的路径
            var path = Directory.CreateDirectory($"{env.WebRootPath}/UploadFiles/images/{DateTime.Now.ToString("yyyyMMdd")}");

            //生成新的文件名  DateTime.Now.ToString("yyyyMMddHHmmss")获取当前时间的年月日时分秒
            var newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{new Random().Next(1000, 9999)}{fileExt}";
            //使用FileStream创建文件流
            using (var fileStream = new FileStream($"{path}/{newFileName}", FileMode.Create))
            {
                formFile.CopyTo(fileStream);
            }

            //构建前台能够访问的一个地址   /UploadFiles/images如果做了分类可以换成分类定义的参数 
            var baseUrl = $"{Request.Scheme}://{Request.Host}/UploadFiles/images/{DateTime.Now.ToString("yyyyMMdd" + "/") + newFileName}";

            return Task.FromResult<IActionResult>(new JsonResult(new { fileName = newFileName, filePath = baseUrl }));
        }

        /// <summary>
        /// 批量删除会议室
        /// </summary>
        [HttpDelete]
        [LogOperation("会议室管理", "删除", "批量删除会议室")]
        public async Task<ApiResult> DeleteMeetingRoomRangeAsync(string Id)
        {
            try
            {
                var result = await _meetingRoomServices.DeleteMeetingRoomRangeAsync(Id);
                if (result.IsSuc)
                {
                    _logger.LogInformation("批量删除会议室成功: {Id}", Id);
                }
                return result;
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("批量删除会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
    }
}
